package com.cy.ppj.comm.third.tg;

import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * okhttp工具类
 *
 */

public class OkHttpUtils {

	private static OkHttpClient okHttpClient;

	static {
		okHttpClient = new OkHttpClient.Builder().build();
	}

	private static final MediaType MEDIA_TYPE_APPLICATION = MediaType.parse("application/octet-stream");
	private static final MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain;charset=utf-8");
	private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json;charset=utf-8");

	/**
	 * http post 上传文件
	 * 
	 * @author cena
	 *
	 */
	public static String upLoadFile(String url, Map<String, Object> params, List<File> fileList) throws Exception {

		MultipartBody.Builder builder = new MultipartBody.Builder();
		// 设置类型
		builder.setType(MultipartBody.FORM);

		// 加参数
		for (String key : params.keySet()) {
			builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
					RequestBody.create(MEDIA_TYPE_TEXT, (String) params.get(key)));
		}

		// 加文件
		for (File file : fileList) {
			builder.addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_APPLICATION, file));
		}

		RequestBody body = builder.build();

		Request request = new Request.Builder().url(url).post(body).build();
		Call call = okHttpClient.newCall(request);

		Response response = call.execute();
		String jsonString = response.body().string();
		return jsonString;
	}

	/**
	 * http post请求json格式
	 * 
	 * @author cena
	 *
	 */
	public static String httpPostWithJson(Map<String, Object> paramsMap, String url) throws Exception {
		// 使用fastjson将对象转换为json字符串
		String json = JSON.toJSONString(paramsMap);
		// MediaType 设置Content-Type 标头中包含的媒体类型值,urlencode防止中文参数乱码
		RequestBody requestBody = FormBody.create(MEDIA_TYPE_JSON, URLEncoder.encode(json, "UTF-8"));

		Request okrequest = new Request.Builder().url(url)// 请求的url
				.post(requestBody).build();
		Call call = okHttpClient.newCall(okrequest);

		Response response = call.execute();
		String jsonString = response.body().string();
		return jsonString;
	}

}